<template>
  <div id="userEdit" >
    <Modal v-model="modal.show" :loading="modal.loading" :title="modal.title" width="700px" :mask-closable="false" :footer-hide=true :closable="false">
      <Form ref="formUser" :model="rowData" label-position="right" :label-width="100" :rules="rules">
        <FormItem :label="$t('code')"><Input v-model="rowData.code" :readonly="modal.readonly" maxlength=255></Input></FormItem>
        <FormItem :label="$t('name')"><Input v-model="rowData.name" :readonly="modal.readonly" maxlength=255></Input></FormItem>
        <FormItem :label="$t('account')"><Input v-model="rowData.loginName" :readonly="modal.readonly" maxlength=255></Input></FormItem>

        <FormItem :label="$t('organization')"><OrganizationTree v-model="rowData.orgId" ref="editOrg" width="200px" :readonly="modal.readonly"/></FormItem>

        <FormItem :label="$t('status')">
          <i-switch v-model="rowData.enabled" true-color="#13ce66" false-color="#ff4949" size="large" :readonly="modal.readonly">
            <span slot="open">{{ $t('endabled') }}</span>
            <span slot="close">{{ $t('disabled') }}</span>
          </i-switch></FormItem>
        <FormItem :label="$t('alarm_push')">
          <i-switch v-model="rowData.enabledNotify" true-color="#13ce66" false-color="#ff4949" size="large" :readonly="modal.readonly">
            <span slot="open">{{ $t('endabled') }}</span>
            <span slot="close">{{ $t('disabled') }}</span>
          </i-switch></FormItem>
        <FormItem :label="$t('user_role_reg')">
          <Transfer
            :data="rolesData"
            :target-keys="targetKeys"
            :titles="titles"
            filterable
            :filter-method="filterMethod"
            @on-change="handleChange"></Transfer>
        </FormItem>
        <FormItem>
          <div style="float: right;">
            <Button v-show="modal.action!='VIEW'" type="primary"  @click="save" >{{ $t('save') }}</Button>
            <Button @click="close">{{ $t('cancel') }}</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import OrganizationTree from '@/components/topnav/OrganizationTree';
import Role from '@/api/role';
import UserRole from '@/api/UserRole';
import {addUser,updateUser} from '@/api/user';
import {apiResult} from "@/libs/util";
export default {
  name: 'userEdit',
  components:{OrganizationTree},
  computed:{
    titles(){
      return[this.$t('all'), this.$t('selectd')]
    },
    rules(){
      return{
        code:[{required: true, message: this.$t('code_must_be_enter'), trigger: 'blur'}],
        name:[{required: true, message: this.$t('name_must_be_enter'), trigger: 'blur'}],
      }
    }
  },
  data(){
    return{
      roleApi: new Role(),
      userRoleApi: new UserRole(),
      modal:{
        show:false,
        loading:false,
        readonly:false,
        title:"",
        action:"VIEW",
        callback:null
      },
      rowData:{
        id:null,
        code:null,
        name:null,
        loginName:null,
        orgId:null,
        enabled:true,
        enabledNotify:true,
        type: 1,
        roles:[]
      },

      /** 可选的所有角色 数据格式｛Key:xxx,label:xxx｝*/
      rolesData: [],
      /** 选择的角色  只有key 如[1]*/
      targetKeys: [],

    }

  },
  methods:{
    openDialog: function (action,row, callback) {
      this.modal.show=true;
      this.modal.readonly=false;
      this.modal.callback = callback;
      this.modal.action = action;

      if (action=="ADD"){
        this.modal.title=this.$t('add');
        this.$refs["formUser"].resetFields();
      }else if (action=="VIEW"){
        this.modal.title=this.$t('browse');
        this.$refs["formUser"].resetFields();
        this.modal.readonly=true;
      }else if (action=="EDIT"){
        this.modal.title=this.$t('edit');
      }
      if (row != null) {
        this.rowData = row;
      }
      /** 查询权限数据 */
      this.getRoleData();

      if (action == "VIEW"){
        for(let i in this.rolesData){
          this.rolesData[i].disabled = true;
        }
      }else{
        for(let i in this.rolesData){
          this.rolesData[i].disabled = false;
        }
      }
    },

    close(){
      this.modal.show=false;
      this.$refs["formUser"].resetFields();
    },
    save(){
      let that = this;
      this.$refs["formUser"].validate((valid) => {
        if (that.modal.action == "VIEW"){that.close();}
        if (valid) {
          //已选择的角色
          that.rowData.roles=[];
          if (!!that.targetKeys){
            for(let i in that.targetKeys){
              if (i<that.targetKeys.length){
                /** 最后一项数据不对，此处忽略 */
                that.rowData.roles.push({id:that.targetKeys[i]});
              }
            }
          }
          if (!that.rowData.code) {
            this.$Message.error(this.$t('code_must_be_enter'));
            return;
          }
          if (!that.rowData.name) {
            this.$Message.error(this.$t('name_must_be_enter'));
            return;
          }
          if (!that.rowData.loginName) {
            this.$Message.error(this.$t('user_account_must_be_enter'));
            return;
          }
          /** 新增 */
          if (that.rowData.id == null){
              addUser(JSON.stringify(that.rowData)).then(res => {
                apiResult(res.data,true,result=>{
                  if (!!that.modal.callback) that.modal.callback();
                  that.close();
                });
            })
          }else{
            updateUser(JSON.stringify(that.rowData)).then(res => {
              apiResult(res.data,true,result=>{
                if (!!that.modal.callback) that.modal.callback();
                that.close();
              });
            })
          }
        } else {
          that.$Message.error(this.$t('data_check_error'));
          return;
        }
      })
    },
    /** 角色选择框 方法汇集 */
    /** 角色选中 */
    handleChange(newTargetKeys) {
      console.log(newTargetKeys);
      this.targetKeys = newTargetKeys;
    },
    /** 角色搜索*/
    filterMethod(data, query) {
      return data.label.indexOf(query) > -1;
    },

    getRoleData(){
      /** 初始化数据，查询所有角色*/
      this.roleApi.queryList().then(res=>{
        apiResult(res.data,false,result=>{
          const readonly = this.modal.action=="VIEW"?true:false;
          this.rolesData = [];
          this.roleList=[];
          for(let i in result.data){
            this.rolesData.push({
              key:result.data[i].id,
              label:result.data[i].code,
              description:result.data[i].name,
              disabled:readonly});
          }
        });

      })

      /** 查询该 用户的权限 **/
      if (!!this.rowData.id){
        this.userRoleApi.queryByUser(JSON.stringify({userId: this.rowData.id})).then(res=>{
          apiResult(res.data,false,result=>{
            this.targetKeys=[];
            for(let i in res.data.data){
              this.targetKeys.push(res.data.data[i].roleId);
            }
          })
        })
      }

    }
  },
  mounted(){

  }
}

</script>
<style lang="less">
@import ".././template";
</style>
